<template>
    <div class="table-page">
        <div class="table-search-box" @keyup.enter="search()">
            <div class="search-item">
                <label>所属学科：</label>
                <div class="table-query-input">
                    <category-select
                        :category-id.sync="queryData.categoryId"
                        :props="{}"
                    />
                </div>
            </div>
            <div class="search-item">
                <label>试卷名称：</label>
                <div class="table-query-input">
                    <el-input
                        v-model="queryData.name"
                        clearable
                        placeholder="试卷名称"
                    ></el-input>
                </div>
                <label>试卷类型：</label>
                <div class="table-query-input">
                    <el-select
                        v-model="queryData.paperType"
                        placeholder="请选择试卷类型"
                        clearable
                    >
                        <el-option
                            v-for="k in Object.keys(paperType)"
                            :key="k"
                            :label="paperType[k].desc"
                            :value="k"
                        ></el-option>
                    </el-select>
                </div>
                <label>来源类型：</label>
                <div class="table-query-input">
                    <el-select
                        v-model="queryData.sourceType"
                        placeholder="试卷来源类型"
                        clearable
                    >
                        <el-option value="0" label="手动加入"
                            >手动加入</el-option
                        >
                        <el-option value="1" label="vers6.0导入"
                            >vers6.0导入</el-option
                        >
                        <el-option value="2" label="才士导入"
                            >才士导入</el-option
                        >
                    </el-select>
                </div>
            </div>
            <div class="search-item">
                <el-button
                    type="primary"
                    icon="el-icon-search"
                    :loading="tableLoading"
                    @click="clickSearch()"
                    >搜索
                </el-button>
            </div>
            <div class="search-item">
                <el-button
                    icon="el-icon-refresh"
                    :loading="tableLoading"
                    @click="resetSearch()"
                    >重置
                </el-button>
            </div>
        </div>
        <div class="table-operation-box">
            <el-button
                type="primary"
                icon="el-icon-plus"
                style="margin-bottom: 2em"
                @click="clickAddPaper()"
                >新增试卷
            </el-button>
            <el-button
                type="danger"
                style="margin-bottom: 2em"
                :disabled="ids.length === 0"
                @click="
                    tableDelete(
                        '/exam/paper/deleted-list',
                        {
                            ids: ids
                        },
                        true
                    )
                "
                >批量删除
            </el-button>
            <el-button
                type="success"
                style="margin-bottom: 2em"
                :disabled="ids.length === 0"
                @click="updateCategory"
                >批量修改学科
            </el-button>
            <el-button
                type="warning"
                style="margin-bottom: 2em"
                icon="el-icon-lock"
                :disabled="ids.length === 0"
                @click="hide(true)"
                >隐藏
            </el-button>
            <el-button
                type="info"
                style="margin-bottom: 2em"
                icon="el-icon-unlock"
                :disabled="ids.length === 0"
                @click="hide(false)"
                >公开
            </el-button>
        </div>
        <div class="table-data-box">
            <el-table
                ref="table"
                v-loading="tableLoading"
                border
                :data="tableData"
                style="width: 100%;min-height:40em"
                row-key="id"
                :highlight-current-row="true"
                @current-change="handleSelectionChange"
                @selection-change="handleSelectionChange2"
            >
                <el-table-column
                    type="selection"
                    min-width="55"
                    align="center"
                    :resizable="false"
                >
                </el-table-column>
                <el-table-column
                    prop="name"
                    label="试卷名称"
                    min-width="150"
                    align="center"
                >
                    <template
                        slot-scope="scope"
                        v-loading="scope.row.opLoading"
                    >
                        <div
                            v-show="!scope.row.nameEdit"
                            @dblclick="scope.row.nameEdit = true"
                        >
                            {{ scope.row.name }}
                        </div>
                        <el-input
                            v-show="scope.row.nameEdit"
                            v-model="scope.row.name"
                            @blur="
                                nameEditSave(
                                    '/exam/paper/change-name',
                                    scope.row,
                                )
                            "
                        ></el-input>
                    </template>
                </el-table-column>
                <el-table-column prop="sort" label="排序" width="150">
                    <template
                        slot-scope="scope"
                        v-loading="scope.row.opLoading"
                    >
                        <div
                            v-show="!scope.row.sortEdit"
                            @dblclick="scope.row.sortEdit = true"
                        >
                            {{ scope.row.sort }}
                        </div>
                        <el-input
                            v-show="scope.row.sortEdit"
                            v-model="scope.row.sort"
                            @blur="
                                sortEditSave(
                                    '/exam/paper/change-sort',
                                    scope.row
                                )
                            "
                        ></el-input>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="categoryName"
                    label="所属学科"
                    min-width="130"
                ></el-table-column>

                <el-table-column
                    prop="oldCategoryName"
                    label="所属学科(原)"
                    min-width="130"
                >
                    <template slot-scope="scope">
                        <span style="color: #aeb4b8">{{ scope.row.oldCategoryName ? scope.row.oldCategoryName : "-" }}</span>
                    </template>
                </el-table-column>

                <el-table-column
                    prop="totalScore"
                    label="试卷总分"
                    width="60"
                ></el-table-column>
                <el-table-column prop="sourceType" label="来源类型" width="100">
                    <template slot-scope="scope">
                        {{
                            scope.row.sourceType === 0
                                ? "手动加工"
                                : scope.row.sourceType === 1
                                ? "vers6.0导入"
                                : "才士导入"
                        }}
                    </template>
                </el-table-column>
                <el-table-column prop="isHide" label="状态" width="100">
                    <template slot-scope="scope">
                        {{ scope.row.isHide ? "隐藏" : "公开" }}
                    </template>
                </el-table-column>
                <el-table-column prop="paperType" label="试卷类型" width="100">
                    <template slot-scope="scope">
                        <k-tag
                            :tag="paperType[scope.row.paperType]"
                            text
                        ></k-tag>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="remark"
                    label="试卷描述"
                    width="120"
                    show-overflow-tooltip
                ></el-table-column>
                <el-table-column
                    prop="createdTime"
                    label="创建时间"
                    width="160"
                ></el-table-column>
                <el-table-column
                    label="操作"
                    align="center"
                    fixed="right"
                    min-width="200"
                >
                    <template slot-scope="scope">
                        <el-button
                            class="primary"
                            type="text"
                            size="mini"
                            icon="el-icon-edit"
                            :loading="scope.row.opLoading"
                            @click="toEditPg(scope.row, 'edit')"
                            >编辑
                        </el-button>
                        <el-button
                            type="text"
                            size="mini"
                            icon="el-icon-check"
                            :loading="scope.row.opLoading"
                            @click="updateCategory(scope.row)"
                            >修改学科
                        </el-button>
                        <el-button
                            v-if="!scope.row.edit"
                            type="text"
                            icon="el-icon-picture-outline"
                            size="mini"
                            :loading="scope.row.opLoading"
                            @click="toEditPg(scope.row, 'see')"
                            >查看试卷
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div v-if="pageData.total" class="xy-between table-page-box">
            <el-pagination
                :current-page.sync="pageData.currentPage"
                :page-sizes="pageData.pageSizes"
                :page-size.sync="pageData.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="pageData.total"
            >
            </el-pagination>
        </div>
        <!-- 试卷弹出框 -->
        <el-dialog title="添加试卷" :visible.sync="addPaperDialog" width="45%">
            <el-form
                ref="paperForm"
                :model="paperForm"
                :rules="paperRules"
                label-width="10em"
                class="data-form"
            >
                <div class="xy-start al-str">
                    <el-form-item label="所属学科" prop="categoryId">
                        <category-select
                            :category-id.sync="paperForm.categoryId"
                            :props="{}"
                        />
                    </el-form-item>
                    <el-form-item label="所属栏目" prop="columnId">
                        <el-select
                            v-model="columnId"
                            clearable
                            placeholder="请选择"
                            @change="handleColumnChange"
                        >
                            <el-option
                                v-for="item in paperColumns"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                </div>
                <div class="xy-start al-str">
                    <el-form-item label="试卷时长" prop="examTime">
                        <el-input
                            v-model.number="paperForm.examTime"
                            clearable
                            placeholder="试卷时长"
                        ></el-input>
                    </el-form-item>
                    <el-form-item label="所属年份" prop="sourceYear">
                        <el-date-picker
                            v-model="paperForm.sourceYear"
                            type="year"
                            value-format="yyyy"
                            placeholder="选择年份"
                        >
                        </el-date-picker>
                    </el-form-item>
                </div>
                <div class="xy-start al-str">
                    <el-form-item label="试卷总分" prop="totalScore">
                        <el-input
                            v-model.number="paperForm.totalScore"
                            clearable
                            placeholder="试卷总分"
                        ></el-input>
                    </el-form-item>
                    <el-form-item label="试卷及格分" prop="passScore">
                        <el-input
                            v-model.number="paperForm.passScore"
                            clearable
                            placeholder="试卷及格分"
                        ></el-input>
                    </el-form-item>
                </div>
                <div class="xy-start al-str">
                    <el-form-item label="试卷名称" prop="name">
                        <el-input
                            v-model="paperForm.name"
                            clearable
                            placeholder="试卷名称"
                        ></el-input>
                    </el-form-item>
                    <el-form-item label="试卷类型" prop="paperTypes">
                        <el-select
                            v-model="paperForm.paperType"
                            clearable
                            placeholder="请选择"
                        >
                            <el-option
                                v-for="k in Object.keys(paperType)"
                                :key="k"
                                :label="paperType[k].desc"
                                :value="k"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                </div>
                <div class="xy-start al-str">
                    <el-form-item label="试卷描述" prop="remark">
                        <el-input
                            v-model="paperForm.remark"
                            type="textarea"
                        ></el-input>
                    </el-form-item>
                </div>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="cancelPaper">取 消</el-button>
                <el-button type="primary" @click="submitPaper('paperForm')"
                    >确 定</el-button
                >
            </span>
        </el-dialog>
        <el-dialog
            title="选择学科"
            :visible.sync="paperCategoryDialog"
            :close-on-click-modal="false"
            width="40%"
        >
            <category-select
                style="width: 100%"
                :category-id.sync="categoryModel.categoryId"
                :props="{}"
            />
            <div slot="footer" class="dialog-footer">
                <el-button @click="cancelCategory">取 消</el-button>
                <el-button type="primary" @click="updateCategorySubmit()">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { TablePage } from "@/layout/mixin/iVue.js";
import { mapState } from "vuex";
import {fetchColumnList, hidePapers, updatePaperCategory} from "@/api/exam";
import { post, put } from "@/api/request";
import CategorySelect from "@/components/CategorySelect";
import category from "@/views/models/exam/base/category.vue";

export default {
    name: "PaperIndex",
    components: { CategorySelect },
    mixins: [TablePage],
    data() {
        let checkPaperNumber = (rule, value, callback) => {
            if (!value) {
                return callback(new Error("不能为空"));
            }
            if (!Number.isInteger(value)) {
                callback(new Error("请输入数字值"));
            } else {
                callback();
            }
        };
        return {
            queryData: {
                name: "",
                paperType: "",
                categoryId: null,
                pageSize: 10,
                currentPage: 1,
                sourceType: ""
            },
            tableData: [],
            ids: [],
            paperId:"",
            addPaperDialog: false,
            paperCategoryDialog:false,
            categoryModel:{
                categoryId:null
            },
            paperColumns: [],
            paperForm: {
                id: null,
                categoryId: null,
                remark: "",
                name: "",
                sourceYear: null,
                examTime: 0,
                totalScore: 0,
                paperType: null,
                integrityState: 0,
                passScore: 0,
                isHide: 0,
                sourceType: 0,
                columnId: "",
                content: []
            },
            columnId: "",
            paperRules: {
                categoryId: [
                    {
                        required: true,
                        message: "请选择一个学科",
                        trigger: "change"
                    }
                ],
                columnId: [
                    {
                        required: true,
                        message: "请选择一个栏目",
                        trigger: "change"
                    }
                ],
                paperType: [
                    {
                        required: true,
                        message: "请选择试卷类型",
                        trigger: "change"
                    }
                ],
                name: [
                    {
                        required: true,
                        message: "请输入试卷名称",
                        trigger: "blur"
                    },
                    {
                        min: 3,
                        max: 30,
                        message: "长度在 3 到 30 个字符",
                        trigger: "blur"
                    }
                ],
                sourceYear: [
                    {
                        required: true,
                        message: "请选择试卷年份",
                        trigger: "change"
                    }
                ],
                examTime: [
                    {
                        required: true,
                        message: "请选择考试时长",
                        validator: checkPaperNumber,
                        trigger: "blur"
                    }
                ],
                totalScore: [
                    {
                        required: true,
                        message: "请填写试卷总分",
                        validator: checkPaperNumber,
                        trigger: "blur"
                    }
                ],
                passScore: [
                    {
                        required: true,
                        message: "请填写试卷及格分",
                        validator: checkPaperNumber,
                        trigger: "blur"
                    }
                ]
            }
        };
    },
    computed: {
        ...mapState({
            status: state => state.status.questionFirstType,
            paperType: state => state.status.paperType
        })
    },
    watch: {
        actionSearch(val) {
            this.$refs.tree.filter(val);
        },
        "paperForm.categoryId"(id) {
            if (id !== undefined) {
                fetchColumnList({ categoryId: id, type: "paperLibrary" }).then(
                    res => {
                        this.paperColumns = Object.assign([], res);
                        this.columnId = "";
                    }
                );
            }
        }
    },
    methods: {
        category() {
            return category
        },
        clearQuery() {
            (this.queryData = {}), this.search();
        },
        search(queryData = {}) {
            this.loadTable("/exam/paper/page", queryData);
        },
        handleSelectionChange(val) {
            this.ids = [];
            const length = val.length;
            for (let n = 0; n < length; n++) {
                ids.push(val[n].id);
            }
        },
        handleSelectionChange2(val) {
            this.ids = [];
            const length = val.length;
            for (let n = 0; n < length; n++) {
                this.ids.push(val[n].id);
            }
        },
        handleColumnChange(vl) {
            this.paperForm.columnId = vl;
        },
        filterAction(value, data) {
            if (!value) return true;
            return data.label.indexOf(value) !== -1;
        },
        clickSelectAction(data, checked, indeterminate) {
            const actionCode = data.id;
            if (checked) {
                this.dataForm.actionCodes.push(actionCode);
            } else {
                this.dataForm.actionCodes.splice(
                    this.dataForm.actionCodes.indexOf(actionCode),
                    1
                );
            }
        },
        toEditPg(data, type) {
            if (type === "see") {
                this.$router.push({
                    name: "SeeQuestionIndex",
                    query: { paperId: data.id, type: type }
                });
            } else {
                this.$router.push({
                    name: "EditQuestionIndex",
                    query: { paperId: data.id, type: type }
                });
            }
        },
        hide(val) {
            hidePapers({
                paperType: this.queryData.paperType,
                ids: this.ids,
                isHide: val
            }).then(res => {
                if (res) {
                    this.search();
                }
            });
        },
        clickAddPaper() {
            // 添加试卷
            this.addPaperDialog = true;
            this.paperForm = {};
        },
        cancelPaper() {
            this.addPaperDialog = false;
            this.paperForm = {};
        },
        submitPaper(formName) {
            this.addPaperDialog = true;
            this.$refs[formName].validate(valid => {
                if (valid) {
                    // 保存到后端
                    this.paperForm.integrityState = 0;
                    this.paperForm.sourceType = 0;
                    this.paperForm.isHide = 0;
                    this.paperForm.content = [];
                    if (
                        this.paperForm.id !== null &&
                        this.paperForm.id !== undefined
                    ) {
                        put("exam/paper/update", this.paperForm).then(data => {
                            if (data) {
                                this.$message({
                                    message: "恭喜你，试卷编辑成功",
                                    type: "success"
                                });
                            }
                        });
                    } else {
                        post("exam/paper/update", this.paperForm).then(data => {
                            if (data) {
                                this.$message({
                                    message: "恭喜你，试卷保存成功",
                                    type: "success"
                                });
                                this.addPaperDialog = false;
                                this.search();
                            }
                        });
                    }
                } else {
                    console.log("error submit!!");
                    return false;
                }
            });
        },
        cancelCategory(){
            this.paperCategoryDialog = false;
            this.categoryModel.categoryId = null;
            this.paperId = "";
        },
        updateCategory(data){
            if(data.id !== null){
               this.paperId = data.id
            }
            this.paperCategoryDialog = true;
        },
        updateCategorySubmit(){
            if(this.categoryModel.categoryId === null){
                return this.$message({
                    message: "请选择学科",
                    type: "warning"
                });
            }
            if(this.ids.length === 0){
                this.ids.push(this.paperId)
            }
            if(this.ids.length === 0){
                return this.$message({
                    message: "请选择一套试卷",
                    type: "warning"
                });
            }

            // 确定提示
            this.$confirm("此操作会将之前配置过的学科栏目下的试卷下架, 修改之后的学科栏目需要重新配置试卷，确定这么操作？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(() => {
                updatePaperCategory({
                    ids: this.ids,
                    categoryId: this.categoryModel.categoryId
                }).then(res => {
                    if (res) {
                        this.search();
                        this.cancelCategory()
                        this.$message({
                            message: "恭喜你，试卷学科修改成功",
                            type: "success"
                        });
                    }
                });
                this.$message({
                    type: "success",
                    message: "修改成功!"
                });
            }).catch(() => {
                this.$message({
                    type: "info",
                    message: "已取消修改"
                });
            });
        }
    }
};
</script>

<style lang="scss" scoped>
.data-form ::v-deep {
    .el-form-item {
        .el-date-editor {
            input {
                width: 92%;
            }
        }
    }
}
.search-item {
    label {
        margin-left: 1em;
    }
}
</style>
